<?php

namespace app\modules\backend\controllers;

use Yii;
use app\tools\Re;
use app\tools\Map;
use app\models\Base;
use app\models\Area;
use app\models\Shop;

class ShopController extends BaseController
{
  public function actionList(){
    $name = Yii::$app->request->post('name', '');
    $page = Yii::$app->request->post('page', 0);
    $page_size = Yii::$app->request->post('page_size', 20);
    $query = Shop::find()->where(['status' => [0,1]]);
    if (!empty($name)) {
      $query->andWhere(['like', 'name', $name]);
    }
    $list = $query->orderBy('created_at desc')->limit($page_size)->offset($page_size*$page)->all();
    $data = [];
    if ($list) {
      foreach($list as $v) {
        $data[] = [
          'id' => $v->id,
          'name' => $v->name,
          'sub_name' => $v->sub_name,
          'logo' => $v->logo,
          'phone' => $v->phone,
          'province_id' => $v->province_id,
          'city_id' => $v->city_id,
          'area_id' => $v->area_id,
          'address' => $v->address,
          'service_time' => $v->service_time,
          'commission_pre' => $v->commission_pre,
          'status' => $v->status,
          'status_name' => $v->status ? '启用' : '禁用',
          'created_time' => date('Y-m-d H:i:s', $v->created_at)
        ];
      }
    }
    return Re::data([
      'data' => $data,
      'totalPage' => $query->count(),
      'currentPage' => $page,
      'perPage' => $page_size
    ]);
  }

  public function actionEdit(){
    $id = Yii::$app->request->post('id', 0);
    $post = Yii::$app->request->post();
    $keys = array_keys($post);
    $first_key = $keys[0];
    if (!$first_key) {
      return;
    }
    $area = Area::findOne($post['area_id']);
    $address = $area->parentArea->parentArea->name.$area->parentArea->name.$area->name.$post['address'];
    $location_arr = Map::getLngLat($address);
    $post['lng'] = $location_arr[0];
    $post['lat'] = $location_arr[1];
    return $this->edit(Shop::class, $id, $post);
  }

  public function actionChangeStatus(){
    $id = Yii::$app->request->post('id', 0);
    $status = Yii::$app->request->post('status', 0);
    $model = Shop::findOne($id);
    if (empty($model)) {
      return Re::data(null, '门店信息读取失败', Re::ERROR);
    }
    $model->status = $status;
    if (!$model->save()) {
      return Re::data(null, '操作失败', Re::ERROR);
    }
    return Re::data();
  }

  public function actionListForSelect(){
    $data = Shop::find()->where(['status' => 1])->select("id, name")->all();
    return Re::data(['data' => $data,]);
  }
}
